package com.wolfcode.controller;

import com.wolfcode.pojo.User;
import com.wolfcode.service.UserService;
import com.wolfcode.vo.UserVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author yinyin
 * @create 2022/08/27 下午 7:55
 */
@Controller
@Slf4j
public class LoginController {
    @Autowired
    private UserService userService;

    //登录
    @PostMapping("login")
    @ResponseBody
    public User  login(@RequestBody UserVo userVo, HttpSession session){
        User user = userService.selectUserByUsername(userVo.getUsername());
        //查询用户是否存在
        if(user==null){
            throw  new RuntimeException("用户不存在");
        };
        //验证密码是否一致
        if(!user.getPassword().equals(userVo.getPassword())){
            throw  new RuntimeException("用户密码输入有误");
        }
        //将用户信息放入会话作用域
        session.setAttribute("SESSION_USER",user);

        return user;
    }
    //登录成功
    @GetMapping("index")
    public String goIndex(HttpSession session){
        User user = (User) session.getAttribute("SESSION_USER");
        if (user!=null){
            return "index";
        }
        return "login";
    }

}
